// Thud - a dynamic object-oriented language
// Copyright (C) 2009,2010 David H. Hovemeyer <david.hovemeyer@gmail.com>

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

#ifndef VM_IPERSISTENT_H
#define VM_IPERSISTENT_H

#include <cstdint>
#include <vector>
#include <memory>
class DataInputStream;
class DataOutputStream;

/**
 * Abstract base class for all objects which can serialize/deserialize
 * to and from streams.
 */
class IPersistent {
public:
	/** Constructor. */
	IPersistent();
	/** Destructor. */
	virtual ~IPersistent();

	/**
	 * Read the serialized representation of this object
	 * from given DataInputStream.
	 */
	virtual void read(DataInputStream *in) = 0;

	/**
	 * Write the serialized representation of this object
	 * to given DataOutputStream.
	 */
	virtual void write(DataOutputStream *out) const = 0;

	/**
	 * Read a sequence of objects into given vector of pointers.
	 *
	 * @param vec     vector of pointers
	 * @param numElts number of objects to read
	 * @param in      the DataInputStream to read from
	 */
	template<class T>
	static void readAll(std::vector<T*> &vec, uint32_t numElts, DataInputStream *in) {
		for (uint32_t i = 0; i < numElts; i++) {
			std::auto_ptr<T> elt(new T());
			elt->read(in);
			vec.push_back(elt.release());
		}
	}

	/**
	 * Write a sequence of objects from given vector of pointers.
	 *
	 * @param vec  vector of pointers
	 * @param out  the DataOutputStream to write to
	 */
	template<class T>
	static void writeAll(const std::vector<T*> &vec, DataOutputStream *out) {
		for (typename std::vector<T*>::const_iterator i = vec.begin(); i != vec.end(); i++) {
			(*i)->write(out);
		}
	}
};

#endif // VM_IPERSISTENT_H
